package org.bluedream.comm.utils;

import java.io.IOException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.util.Base64;

public class EncryptUtil {
    private EncryptUtil() {
        throw new AssertionError();
    }

    /**
     * 将传入的字符串按指定方式加密
     * @param str
     * @param method
     * @return
     */
    private static String encode(String str , String method){
        MessageDigest md ;
        String dstr = null;
        try {
            md = MessageDigest.getInstance(method);
            md.update(str.getBytes());
            dstr = new BigInteger(1,md.digest()).toString(16);
        }catch (Exception e){
            e.printStackTrace();
        }
        return dstr;
    }

    /**
     * 用base64算法加密
     * @param str
     * @return
     */
    public static String encodeBase64String(String str){
        return encodeBase64String(str.getBytes());
    }

    /**
     * 用base64算法加密
     * @param bytes
     * @return
     */
    public static String encodeBase64String(byte[] bytes){
        Base64.Encoder encoder = Base64.getEncoder();
        return encoder.encodeToString(bytes);
    }

    /**
     * 用MD5算法加密
     * @param str
     * @return
     */
    public static String encodeMD5String(String str){
        return encode(str , "MD5").toUpperCase();
    }

    /**
     * SHA算法加密
     * @param str
     * @return
     */
    public static String encodeSHAString(String str){
        return encode(str , "SHA");
    }

    /**
     * MD5加密后的字符串转Base64
     * @param str
     * @return
     */
    public static String encodeMD5ToBase64String(String str){
        return encodeBase64String(encodeMD5String(str));
    }

    /**
     * 用base64算法解密
     * @param str
     * @return
     * @throws IOException
     */
    public static String decodeBase64String(String str) throws Exception {
        Base64.Decoder decoder = Base64.getDecoder();
        return new String(decoder.decode(str.replaceAll(" " , "+")));
//        return new String(encoder.decodeBuffer(str));
    }

    public static byte[] decodeBase64Byte(String str){
        Base64.Decoder decoder = Base64.getDecoder();
        return decoder.decode(str.replaceAll(" " , "+"));
    }


    public static void main(String[] args) throws Exception {
        String str = "123";
        str = encodeBase64String(str);
        System.out.println(str);
        System.out.println(decodeBase64String(str));
    }
}

